package cn.aitrox.ry.service.image.dao.impl;

import cn.aitrox.ry.service.image.dao.ImageInfoDao;
import cn.aitrox.ry.service.image.entity.ImageInfoMongoEntity;
import cn.aitrox.ry.service.image.repository.ImageInfoRepository;
import cn.aitrox.ry.util.ArrayUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class ImageInfoDaoImpl implements ImageInfoDao {

    @Autowired
    private ImageInfoRepository repository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<ImageInfoMongoEntity> query(List<String> groups, String groupType, List<String> modeList) {
        if (ArrayUtil.isEmpty(groups) || StringUtils.isEmpty(groupType)) {
            return new ArrayList<>();
        }

        Query query = new Query();
        query.addCriteria(Criteria.where(ImageInfoMongoEntity.FIELD_GROUP).in(groups));
        query.addCriteria(Criteria.where(ImageInfoMongoEntity.FIELD_GROUP_TYPE).is(groupType));
        if (!ArrayUtil.isEmpty(modeList)) {
            query.addCriteria(Criteria.where(ImageInfoMongoEntity.FIELD_MODE).in(modeList));
        }
        return mongoTemplate.find(query, ImageInfoMongoEntity.class);

    }

    @Override
    public void save(ImageInfoMongoEntity imageInfo) {
        repository.save(imageInfo);
    }

    @Override
    public void deleteByGroupGroupTypeMode(String group, String groupType, String mode) {
        Query query = new Query();
        query.addCriteria(Criteria.where(ImageInfoMongoEntity.FIELD_GROUP).is(group));
        query.addCriteria(Criteria.where(ImageInfoMongoEntity.FIELD_GROUP_TYPE).is(groupType));
        query.addCriteria(Criteria.where(ImageInfoMongoEntity.FIELD_MODE).is(mode));
        mongoTemplate.remove(query, ImageInfoMongoEntity.class);
    }
}
